import 'package:flutter/material.dart';
import 'package:flutter_screenutil/flutter_screenutil.dart';
import 'package:get/get.dart';
import 'package:squat_easy/generated/assets.dart';
import 'package:squat_easy/se_coin_shop/se_coin_shop_page.dart';
import 'package:squat_easy/se_main/se_mine/se_about/se_about_page.dart';
import 'package:squat_easy/se_main/se_mine/se_edit_info/se_edit_info_page.dart';
import 'package:squat_easy/se_main/se_mine/se_setting/se_setting_page.dart';
import 'package:squat_easy/se_route.dart';
import 'package:squat_easy/se_service/se_log_service.dart';
import 'package:squat_easy/se_service/se_user_service.dart';
import 'package:squat_easy/se_ui/se_dialogs.dart';
import 'package:squat_easy/se_voice_record/se_record_overlay.dart';
import 'package:ylm_ui_kit/ylm_ui_kit.dart';

import 'se_mine_logic.dart';

class SeMinePage extends StatefulWidget {
  const SeMinePage(this.logic, {Key? key}) : super(key: key);

  final SeMineLogic logic;

  @override
  State<SeMinePage> createState() => _SeMinePageState();
}

class _SeMinePageState extends State<SeMinePage> with AutomaticKeepAliveClientMixin {
  @override
  Widget build(BuildContext context) {
    super.build(context);
    return _SeMinePage(widget.logic);
  }

  @override
  bool get wantKeepAlive => true;
}

class _SeMinePage extends StatelessWidget {
  _SeMinePage(this.logic);

  final SeMineLogic logic;

  @override
  Widget build(BuildContext context) {
    return BaseScaffold(
      hideBackBtn: true,
      child: GetBuilder<SeMineLogic>(
        builder: (logic) {
          return Stack(
            fit: StackFit.expand,
            children: [
              _buildBg().positioned(
                top: 0,
                left: 0,
                right: 0,
                bottom: -(50.w + ScreenUtil().bottomBarHeight * 0.5),
              ),
              ValueListenableBuilder(
                valueListenable: SeUserService.instance.notifierOfMineInfo,
                builder: (BuildContext context, SeMineInfoBean value, Widget? child) {
                  return Column(
                    crossAxisAlignment: CrossAxisAlignment.start,
                    children: [
                      _buildAvatar().center().paddingTop(145.w),
                      _buildName().center().padding(top: 12.w),
                      _buildId().center().padding(top: 5.w),
                      _buildBalance().center().padding(top: 20.w),
                      _buildList().padding(top: 20.w),
                    ],
                  );
                },
              ),
            ],
          );
        },
      ),
    );
  }

  Widget _buildBg() => const IconWidget.image(Assets.pngMineBg2, fit: BoxFit.fill);

  Widget _buildBalance() {
    return ButtonWidget(
      width: 310.w,
      height: 94.w,
      alignment: Alignment.center,
      borderWidth: 1.w,
      borderColor: Colors.black,
      borderRadius: 22.w,
      gradient: const LinearGradient(
        colors: [Color(0XFFE3F6F2), Color(0XFFFEFAF1)],
        begin: Alignment(0.6, 1),
        end: Alignment(0.6, 0.3),
      ),
      onTap: () {
        SeRoute.open(const SeCoinShopPage());
        SeLogManager.stat(page: SeLogPage.purchase);
      },
      child: Row(
        mainAxisAlignment: MainAxisAlignment.center,
        children: [
          IconWidget.image(Assets.pngCoin, width: 64.w, height: 64.w).expanded(),
          Container(
            width: 1.w,
            height: 48.w,
            color: Colors.black,
          ),
          Column(
            mainAxisSize: MainAxisSize.min,
            children: [
              const TextWidget.oneLine(
                text: 'My Coins',
                fontSize: 14,
              ),
              TextWidget.oneLine(
                text: (SeUserService.instance.notifierOfMineInfo.value.availableCoins ?? 0).toString().toMoney,
                fontSize: 24,
              ).paddingTop(5.w),
            ],
          ).center().expanded(),
        ],
      ),
    );
  }

  Widget _buildAvatar() {
    String avatar = SeUserService.instance.notifierOfMineInfo.value.avatarThumbUrl ?? '';
    bool editAvatar = CommonStorage().getBool(SeUserService.instance.editAvatarKey, defaultValue: false);
    return Stack(
      children: [
        ButtonWidget(
          child: ImageWidget.url(
            editAvatar ? avatar : '',
            width: 120.w,
            height: 120.w,
            radius: 120.w,
            placeholder: ImageWidget.asset(Assets.pngDefaultAvatar, width: 120.w, height: 120.w, radius: 120.w),
          ),
          onTap: () => SeRoute.open(const SeEditInfoPage()),
        ),
        ButtonWidget(
          onTap: () => SeRoute.open(const SeEditInfoPage()),
          hasInkWell: false,
          child: IconWidget.image(Assets.pngAvatarEdit, size: 32.w),
        ).positioned(top: 0, right: 3.w),
      ],
    );
  }

  Widget _buildName() {
    return TextWidget.oneLine(
      text: SeUserService.instance.notifierOfMineInfo.value.nickname ?? '',
      fontSize: 20,
    );
  }

  OverlayEntry? overlayEntry;

  void _showOverlay() {
    overlayEntry = OverlayEntry(
      builder: (context) => SeRecordOverlay(
        onClose: _removeOverlay,
        onCompleted: (int fileDuration, String path, String fileName, int fileSize) {
          logic.saveAudio(fileName);
        },
      ),
    );
    Overlay.of(Get.overlayContext!).insert(overlayEntry!);
  }

  void _removeOverlay() {
    overlayEntry?.remove();
    overlayEntry = null;
  }

  Widget _buildList() {
    List<Widget> children = [
      _buildItem(
        'Phonetics',
        '',
        () async {
          if (logic.audioName.notEmpty) {
            ///播放
            logic.playAudio();
          } else {
            ///权限判断
            CommonPrivilegeStatus status = await CommonPrivilege.microphone();
            if (!status.result) {
              SeDialogs.twoButton(
                title: status.title,
                description: status.message,
                cancelTitle: YlmGlobalConfig().actionSheetConfig.cancelTitle,
                confirmTitle: YlmGlobalConfig().actionSheetConfig.confirmTitle,
                onConfirm: () => CommonPrivilege.openSettings(),
              );
              return;
            }

            ///录制
            if (overlayEntry == null) {
              _showOverlay();
            } else {
              _removeOverlay();
            }
          }
        },
        right: IconWidget.image(
          logic.audioName.notEmpty ? Assets.pngMineAudioPlay : Assets.pngMineRecord,
          size: 24.w,
        ).paddingRight(48.w),
      ),
      _buildItem('About', Assets.pngMineArrow, () {
        SeRoute.open(const SeAboutPage());
      }),
      _buildItem('Setting', Assets.pngMineArrow, () {
        SeRoute.open(SeSettingPage());
      }),
    ];
    return ListView.separated(
      shrinkWrap: true,
      physics: const NeverScrollableScrollPhysics(),
      padding: EdgeInsets.symmetric(vertical: 0, horizontal: 33.w),
      itemCount: children.length,
      itemBuilder: (BuildContext context, int index) => children[index],
      separatorBuilder: (BuildContext context, int index) => CommonMargin.height(20.w),
    );
  }

  Widget _buildItem(String title, String icon, VoidCallback onTap, {Widget? right}) {
    return ButtonWidget(
      onTap: onTap,
      hasInkWell: false,
      height: 60.w,
      borderRadius: 12.w,
      backgroundColor: Colors.black,
      child: Row(
        children: [
          TextWidget.oneLine(
            text: title,
            fontSize: 18,
            color: Colors.white,
          ).paddingLeft(20.w).expanded(),
          right ?? IconWidget.image(icon, size: 40.w).paddingRight(40.w),
        ],
      ),
    );
  }

  Widget _buildId() {
    return Row(
      mainAxisSize: MainAxisSize.min,
      children: [
        TextWidget.oneLine(
          text: 'ID：${SeUserService.instance.notifierOfMineInfo.value.userId ?? ''}',
          fontSize: 16,
        ).flexible(),
        ButtonWidget.icon(
          const IconWidget.image(Assets.pngCopyColor),
          width: 32.w,
          height: 16.w,
          onTap: () => CommonOperate.copy(
            SeUserService.instance.notifierOfMineInfo.value.userId ?? '',
            toast: 'Copy Success',
          ),
        ).paddingLeft(10.w),
      ],
    );
  }
}
